package com.mk.api.sys;

import com.baomidou.mybatisplus.plugins.Page;
import com.mk.base.controller.BaseController;
import com.mk.base.model.response.Rsp;
import com.mk.base.model.response.RspPage;
import com.mk.model.entity.User;
import com.mk.model.request.UserRequest;
import com.mk.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 1:39 PM 3/14/18
 */
@RestController
@RequestMapping("/user")
public class UserApi extends BaseController {

    @Autowired
    private IUserService userService;

    @RequestMapping(method = RequestMethod.POST)
    public Rsp saveUser(@RequestBody UserRequest request){
        try{
            return Rsp.SUCCESS(userService.saveUser(request));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(method = RequestMethod.PUT)
    public Rsp updateUser(@RequestBody UserRequest request){
        try{
            if(userService.updateUser(request))
                return Rsp.SUCCESS("编辑用户信息成功");
            else
                return Rsp.ERROR("编辑用户信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Rsp deleteUser(@PathVariable("id") Long id){
        try{
            if(userService.deleteUser(id))
                return Rsp.SUCCESS("删除用户信息成功");
            else
                return Rsp.ERROR("删除用户信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/modify/pwd",method = RequestMethod.POST)
    public Rsp modifyPwd(@RequestBody UserRequest request){
        try{
            if(userService.modifyPassword(request))
                return Rsp.SUCCESS("修改密码成功");
            else
                return Rsp.ERROR("修改密码失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Rsp findOne(@PathVariable("id") Long id){
        try{
            return Rsp.SUCCESS(userService.get(id));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/page",method = RequestMethod.GET)
    public RspPage findAll(UserRequest request){
        Page<User> page = userService.getPage(request,getPagination(request));
        return convertSuccessPage(page);
    }
}